/**
 * FormFinalizar.java
 * Copyright (C) 2009 Jose Mauro da Silva Sandy
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 *  Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
 */

/*
 * FormFinalizar.java
 *
 * Created on 10/05/2009, 01:35:51
 */

package frames;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import javax.swing.JOptionPane;
import javax.swing.JTable;
import javax.swing.ListSelectionModel;
import javax.swing.table.DefaultTableModel;
import negocio.movimento.Movimento;
import negocio.pessoas.Empreendimento;
import negocio.pessoas.Pessoa;
import utils.ErrorMessage;
import utils.GenerateID;
import utils.StatusEmpreendimento;
import utils.TipoMovimento;

/**
 *
 * @author jmsandy
 */
public class FormFinalizar extends javax.swing.JDialog {

    //<editor-fold defaultstate="collapsed" desc="FIELDS">
    private ArrayList lstObj           = null;
    //</editor-fold>

    //<editor-fold defaultstate="collapsed" desc="Constructor">
    /** Creates new form FormFinalizar */
    public FormFinalizar() {
        initComponents();
        initalizeMyComponentes();
    }
    //</editor-fold>

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jScrollPane1 = new javax.swing.JScrollPane();
        tableFinalizar = new javax.swing.JTable();
        panelBotao = new javax.swing.JPanel();
        btnConfirmar = new javax.swing.JButton();
        btnCancelar = new javax.swing.JButton();

        setTitle("Finalizar Empreendimento");
        setName("formFinalizar"); // NOI18N
        setResizable(false);

        tableFinalizar.setFont(new java.awt.Font("SansSerif", 0, 12)); // NOI18N
        tableFinalizar.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "Empreendimento", "Finalizar"
            }
        ) {
            Class[] types = new Class [] {
                java.lang.String.class, java.lang.Boolean.class
            };
            boolean[] canEdit = new boolean [] {
                false, true
            };

            public Class getColumnClass(int columnIndex) {
                return types [columnIndex];
            }

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        jScrollPane1.setViewportView(tableFinalizar);

        panelBotao.setBorder(javax.swing.BorderFactory.createEtchedBorder(null, java.awt.Color.gray));
        panelBotao.setFont(new java.awt.Font("DejaVu Sans", 0, 12));

        btnConfirmar.setFont(new java.awt.Font("SansSerif", 0, 12)); // NOI18N
        btnConfirmar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/ok.png"))); // NOI18N
        btnConfirmar.setText("Confirmar");
        btnConfirmar.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                btnConfirmarMouseClicked(evt);
            }
        });

        btnCancelar.setFont(new java.awt.Font("SansSerif", 0, 12));
        btnCancelar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/cancel.png"))); // NOI18N
        btnCancelar.setText("Cancelar");
        btnCancelar.setMaximumSize(new java.awt.Dimension(92, 34));
        btnCancelar.setMinimumSize(new java.awt.Dimension(92, 34));
        btnCancelar.setPreferredSize(new java.awt.Dimension(92, 34));
        btnCancelar.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                btnCancelarMouseClicked(evt);
            }
        });

        javax.swing.GroupLayout panelBotaoLayout = new javax.swing.GroupLayout(panelBotao);
        panelBotao.setLayout(panelBotaoLayout);
        panelBotaoLayout.setHorizontalGroup(
            panelBotaoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, panelBotaoLayout.createSequentialGroup()
                .addContainerGap(61, Short.MAX_VALUE)
                .addComponent(btnConfirmar, javax.swing.GroupLayout.PREFERRED_SIZE, 120, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(btnCancelar, javax.swing.GroupLayout.PREFERRED_SIZE, 120, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(59, 59, 59))
        );

        panelBotaoLayout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {btnCancelar, btnConfirmar});

        panelBotaoLayout.setVerticalGroup(
            panelBotaoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, panelBotaoLayout.createSequentialGroup()
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addGroup(panelBotaoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE, false)
                    .addComponent(btnConfirmar)
                    .addComponent(btnCancelar, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap())
        );

        panelBotaoLayout.linkSize(javax.swing.SwingConstants.VERTICAL, new java.awt.Component[] {btnCancelar, btnConfirmar});

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 375, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(panelBotao, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 240, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(panelBotao, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        java.awt.Dimension screenSize = java.awt.Toolkit.getDefaultToolkit().getScreenSize();
        setBounds((screenSize.width-410)/2, (screenSize.height-366)/2, 410, 366);
    }// </editor-fold>//GEN-END:initComponents

    /**
    * @param args the command line arguments
    */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new FormFinalizar().setVisible(true);
            }
        });
    }

    //<editor-fold defaultstate="collapsed" desc="Events">
    // Fecha o formulario
    private void btnCancelarMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_btnCancelarMouseClicked
        dispose();
    }//GEN-LAST:event_btnCancelarMouseClicked

    private void btnConfirmarMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_btnConfirmarMouseClicked
        if(btnConfirmar.isEnabled()){
            // Recupera todos os registros selecionados
            ArrayList<Empreendimento> lstEmp = getLstSelecionados();

            // Verifica se foi selecionado algum registro
            if(lstEmp.size() > 0){

                // Realiza a confirmacao do movimento
                if(JOptionPane.showConfirmDialog(this, "Confirma a finalização"
                     +" dos Empreendimentos selecionados?", "Confirmation",
                     JOptionPane.OK_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE)
                                                    == JOptionPane.OK_OPTION){
                    ArrayList<Movimento> lstMov = createListMovement(lstEmp);

                    try{
                        boolean ret =
                               (new Movimento()).gerarMovimento(lstEmp, lstMov);

                        if(ret){
                            showMessageInformation(
                                               ErrorMessage.MSG_FINAL_INSERCAO);
                            dispose();
                        }
                    }
                    catch(IOException ex){
                        showMessageError(ErrorMessage.MSG_GERAL_BANCO);
                    }
                }
            }
            else{
                showMessageError(ErrorMessage.MSG_FINAL_SELECAO);
            }
        }
    }//GEN-LAST:event_btnConfirmarMouseClicked
    //</editor-fold>

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnCancelar;
    private javax.swing.JButton btnConfirmar;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JPanel panelBotao;
    private javax.swing.JTable tableFinalizar;
    // End of variables declaration//GEN-END:variables

    //<editor-fold defaultstate="collapsed" desc="Methods">
    // Messagem de erro
    private void showMessageError(String msg){
        JOptionPane.showMessageDialog(this, msg, "Finalizar Empreendimento",
                                                    JOptionPane.ERROR_MESSAGE);
    }

    // Messagem de alerta
    private void showMessageInformation(String msg){
        JOptionPane.showMessageDialog(this, msg, "Finalizar Empreendimento",
                                               JOptionPane.INFORMATION_MESSAGE);
    }

    // Inicializa as colunas padroes da tabela
    private void initializeTable(){
        tableFinalizar.getColumnModel().getColumn(0).setPreferredWidth(300);
        tableFinalizar.getColumnModel().getColumn(0).setResizable(false);
        tableFinalizar.getColumnModel().getColumn(1).setPreferredWidth(70);
        tableFinalizar.getColumnModel().getColumn(1).setResizable(false);

        tableFinalizar.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
        tableFinalizar.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
    }

    // Inicializa os componentes
    private void initalizeMyComponentes(){
        initializeTable();
        showRecords();
        enableButton();
    }

    // Habilita os botoes
    private void enableButton(){
        if(tableFinalizar.getModel().getRowCount() > 0){
            btnConfirmar.setEnabled(true);
        }
        else{
            btnConfirmar.setEnabled(false);
        }
    }

    // Recupera e apresenta a lista de objeto
    private void showRecords(){
        DefaultTableModel dtm = (DefaultTableModel)tableFinalizar.getModel();
        tableFinalizar.updateUI();

        // Recupera a lista de Empreendimentos em Aberto
        lstObj = new ArrayList();
        lstObj = (new Pessoa()).recLstEmpreendimentosAtivo();

        // Insere os registros na tabela
        for(Pessoa p : (ArrayList<Pessoa>)lstObj){
            Object[] row = new Object[]{p.getNome(), false};
            dtm.addRow(row);
        }
    }

    // Recupera todos os registros selecionados
    private ArrayList<Empreendimento> getLstSelecionados(){
        ArrayList<Empreendimento> lstEmp = new ArrayList<Empreendimento>();

        // Percorre a lista de registro para pegar os selecionados
        DefaultTableModel def = (DefaultTableModel)tableFinalizar.getModel();
        for(int i = 0; i < tableFinalizar.getRowCount(); i++){
            Object select = (Boolean)tableFinalizar.getValueAt(i, 1);

            // Verifica se o objeto esta selecionado
            if(Boolean.parseBoolean(select.toString())){
                Pessoa p = (Pessoa) lstObj.get(i);
                Empreendimento emp = (new Empreendimento()).
                                    recEmpreendimentoPessoa(p.getCod_objeto());
                emp.setStatus(StatusEmpreendimento.FINALIZADO);
                emp.setDataTermEfetivo(new Date());
                lstEmp.add(emp);
            }
        }
        return lstEmp;
    }

    // Cria lista de movimentos
    private ArrayList<Movimento> createListMovement
                                            (ArrayList<Empreendimento> lstEmp){
        ArrayList<Movimento> lstMov = new ArrayList<Movimento>();

        // Percorre toda a lista de empreendimento e cria um movimento para cada
        // Empreendimento selecionado
        for(Empreendimento emp : lstEmp){
            Movimento mov = new Movimento();
            mov.setCod_objeto(GenerateID.gerarID());
            mov.setEmpreendimento(emp.getCod_objeto());
            mov.setTipoMovimento(TipoMovimento.FINALIZACAO);

            lstMov.add(mov);
        }

        return lstMov;
    }
    //</editor-fold>

}
